<?php 
global $_GPC, $_W;
$shopid=check_right(2);
if(!$shopid)message("请先选择需要管理的店铺",$this->createWebUrl('shop'),'error');
$shop=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_group')." WHERE weid = '{$_W['uniacid']}' and id='".$shopid."'");
$operation = !empty($_GPC['op']) ? $_GPC['op'] : 'display';
$cfg = $this->module['config'];
load()->model('mc');
$grouptemp=mc_groups();
$groupAry=array();
$groupAry[0]="";
$defaultGid=0;
foreach(mc_groups() as $row){
	if($row['isdefault'])$defaultGid=$row['groupid'];
	$groupAry[$row['groupid']]=$row['title'];
}

if($operation=="display"){
	$isno = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' order by id desc  ");
	if($isno && $defaultGid){
		pdo_update('j_hmoney_membercard',array('gid'=>$defaultGid),array('groupid'=>$shopid,'gid'=>'0'));
	}
	$pindex = max(1, intval($_GPC['page']));
	$psize = 10;
	$condition = "  ";
	if(isset($_GPC['keyword']))$condition.= " and (realname like '%" . $_GPC['keyword'] . "%' or cardno like '%" . $_GPC['keyword'] . "%' mobile like '%" . $_GPC['keyword'] . "%')";
	
	$list = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition order by id desc  LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	if($cfg['isgeneralbalance']){
		if(isset($_GPC['keyword']))$condition.= " and (a.realname like '%" . $_GPC['keyword'] . "%' or a.cardno like '%" . $_GPC['keyword'] . "%' a.mobile like '%" . $_GPC['keyword'] . "%')";
		$list = pdo_fetchall("SELECT a.*,b.credit1,b.credit2 FROM ".tablename('j_hmoney_membercard') ." a left join ".tablename('mc_members')." b on a.uid=b.uid WHERE a.weid = '{$_W['uniacid']}' $condition order by a.status asc,a.openid desc,a.id  desc  LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	}
	for($i=0;$i<count($list);$i++){
		$temp1=$this->_2money((($list[$i]['credit']*100+$list[$i]['credit1']*100)));
		$list[$i]['credit']=$temp1;
		$temp2=$this->_2money((($list[$i]['cash']+$list[$i]['credit2']*100)));
		$list[$i]['cash']=$temp2;
	}
	$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition");
	
}elseif ($operation == 'getmemberpage') {
	$pindex = max(1, intval($_GPC['page']));
	$psize = 10;
	$condition = "  ";
	if(isset($_GPC['keyword']))$condition.= " and (realname like '%" . $_GPC['keyword'] . "%' or cardno like '%" . $_GPC['keyword'] . "%' mobile like '%" . $_GPC['keyword'] . "%')";
	$list = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition order by id desc  LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	if($cfg['isgeneralbalance']){
		if(isset($_GPC['keyword']))$condition.= " and (a.realname like '%" . $_GPC['keyword'] . "%' or a.cardno like '%" . $_GPC['keyword'] . "%' a.mobile like '%" . $_GPC['keyword'] . "%')";
		$list = pdo_fetchall("SELECT a.*,b.credit1,b.credit2 FROM ".tablename('j_hmoney_membercard') ." a left join ".tablename('mc_members')." b on a.uid=b.uid WHERE a.weid = '{$_W['uniacid']}' $condition order by a.status asc,a.openid desc,a.id  desc  LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	}
	for($i=0;$i<count($list);$i++){
		$temp1=$this->_2money((($list[$i]['credit']*100+$list[$i]['credit1']*100)));
		$list[$i]['credit']=$temp1;
		$temp2=$this->_2money((($list[$i]['cash']+$list[$i]['credit2']*100)));
		$list[$i]['cash']=$temp2;
	}
	die(json_encode(array('success'=>true,'list'=>$list)));
	
}elseif ($operation == 'postmember') {
	$id=intval($_GPC['id']);
	$data=array(
		"weid"=>$_W["uniacid"],
		"groupid"=>$shopid,
		"cardno"=>$_GPC["cardno"],
		"userid"=>$userid,
		"gid"=>$_GPC["gid"],
		/*"cash"=>intval($_GPC["cash"]*100),
		"credit"=>$_GPC["credit"],*/
		"realname"=>$_GPC["realname"],
		"sex"=>$_GPC["sex"],
		"mobile"=>$_GPC["mobile"],
		"wxcardno"=>$_GPC["wxcardno"],
		"remark"=>$_GPC["remark"],
		"endtime"=>$_GPC["endtime"],
		"status"=>$_GPC["status"],
		"birdday"=>$_GPC["birdday"],
		"label"=>$_GPC["label"],
	);
	$update=array(
		"cardno"=>$data["cardno"],
		"wxcardno"=>$data["wxcardno"],
	);
	if($id){
		unset($data['userid']);
		unset($data['groupid']);
		$isused=pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_membercard') . " WHERE weid=:c and cardno=:b and id<>:a ",array(":a"=>$id,":b"=>$data['cardno'],":c"=>$_W['uniacid']));
		if($isused)die(json_encode(array('success'=>false,'msg'=>"实体卡号重复")));
		if($_GPC["mmEdit_wxcardno"]){
			$isused=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_membercard')." WHERE weid=:c and wxcardno=:b and id<>:a ",array(":a"=>$id,":c"=>$_W['uniacid'],":b"=>$data['wxcardno']));
			if($isused)die(json_encode(array('success'=>false,'msg'=>"微信卡号重复")));
		}
		pdo_update("j_hmoney_membercard",$data,array("id"=>$id));
		$member=pdo_fetch("SELECT * FROM ".tablename('j_hmoney_membercard')." WHERE id=:a ",array(":a"=>$id));
		$update['uid']=$member['uid'];
		$update['openid']=$member['openid'];
	}else{
		$isused=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_membercard')." WHERE weid=:c and cardno=:b ",array(":b"=>$data['cardno'],":c"=>$_W['uniacid']));
		if($isused)die(json_encode(array('success'=>false,'msg'=>"实体卡号重复")));
		if($_GPC["mmEdit_wxcardno"]){
			$isused=pdo_fetchcolumn("SELECT count(*) FROM ".tablename('j_hmoney_membercard')." WHERE weid=:c and wxcardno=:b ",array(":c"=>$_W['uniacid'],":b"=>$data['wxcardno']));
			if($isused)die(json_encode(array('success'=>false,'msg'=>"微信卡号重复")));
		}
		pdo_insert("j_hmoney_membercard",$data);
		$id=pdo_insertid();
	}
	if($update['wxcardno'] && $cfg['wxmembercard'] && (!$update['openid'] || !$update['uid'])){
		//echo "1234";
		//通过卡号获取openid
		$acid=pdo_fetchcolumn("SELECT acid FROM ".tablename('account')." WHERE uniacid=:uniacid ",array(':uniacid'=>$_W['uniacid']));
		$acc = WeAccount::create($acid);
		$tokens=$acc->fetch_token();
		$pageparama=json_encode(array("card_id"=>$cfg['wxmembercard'],"code"=>$update['wxcardno']));
		$resp = ihttp_request("https://api.weixin.qq.com/card/membercard/userinfo/get?access_token=".$tokens,$pageparama, $xml);
		$result=@json_decode($resp['content'],true);
		var_dump($result);
		if(!$result['errcode']){
			$openid=$result['openid'];
			$uid=mc_openid2uid($openid);
			pdo_update("j_hmoney_membercard",array("openid"=>$openid,"uid"=>$uid),array("id"=>$id));
			$this->memberCardInform($id);
		}
	}
	die(json_encode(array('success'=>true)));

}elseif ($operation == 'deletemember') {	
	$id = intval($_GPC['id']);
	$item = pdo_fetch("SELECT id FROM " . tablename('j_hmoney_membercard') . " WHERE  id = '".$id."' ");
	if (empty($item))message('抱歉，不存在或是已经被删除！', $this -> createWebUrl('member'), 'error');
	pdo_delete('j_hmoney_membercard', array('id' => $id));
	message('删除成功！', $this -> createWebUrl('member'), 'success');
	
}elseif ($operation == 'getmember') {
	$id=$_GPC['id'];
	$keyword=trim($_GPC['keyword']);
	if($keyword){
		$condition = "  and (cardno =:a or wxcardno=:a or mobile=:a) ";
		$list = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition order by id desc",array(":a"=>$keyword));
		if($cfg['isgeneralbalance']){
			$condition= " and (a.cardno =:a or a.wxcardno=:a or a.mobile=:a)";
			$list = pdo_fetchall("SELECT a.*,b.credit1,b.credit2 FROM ".tablename('j_hmoney_membercard') ." a left join ".tablename('mc_members')." b on a.uid=b.uid WHERE a.weid = '{$_W['uniacid']}' $condition order by a.status asc,a.openid desc,a.id  desc ",array(":a"=>$keyword));
		}
		if($list){
			for($i=0;$i<count($list);$i++){
				$temp1=$this->_2money((($list[$i]['credit']*100+$list[$i]['credit1']*100)));
				$list[$i]['credit']=$temp1;
				$temp2=$this->_2money((($list[$i]['cash']+$list[$i]['credit2']*100)));
				$list[$i]['cash']=$temp2;
				$list[$i]['level']=$groupAry[$list[$i]['gid']];
			}
		}
		die(json_encode(array('success'=>true,'list'=>$list)));
	}
	if(!$id)die(json_encode(array('success'=>false,'msg'=>"请输入ID号")));
	$member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$id));
	if($cfg['isgeneralbalance']){
		$member = pdo_fetch("SELECT a.*,b.credit1,b.credit2 FROM ".tablename('j_hmoney_membercard') ." a left join ".tablename('mc_members')." b on a.uid=b.uid WHERE a.id=:a  ",array(":a"=>$id));
	}
	$temp1=$this->_2money((($member['credit']*100+$member['credit1']*100)));
	$member['credit']=$temp1;
	$temp2=$this->_2money((($member['cash']+intval($member['credit2']*100))));
	$member['cash']=$temp2;
	$member['bird']=$member['birdday'] ? date("m/d",$member['birdday']) : "";
	$member['level']=$groupAry[$member['gid']];
	die(json_encode(array('success'=>true,'item'=>$member)));
	
}elseif ($operation == 'getmemberinfo') {
	$id=$_GPC['id'];
	if(!$id)die(json_encode(array('success'=>false,'msg'=>"请输入ID号")));
	$member = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition and id=:a ",array(":a"=>$id));
	if(!$member)die(json_encode(array('success'=>false,'msg'=>"请输入ID号")));
	if($cfg['isgeneralbalance']){
		$member = pdo_fetch("SELECT a.*,b.credit1,b.credit2 FROM ".tablename('j_hmoney_membercard') ." a left join ".tablename('mc_members')." b on a.uid=b.uid WHERE a.id=:a  ",array(":a"=>$id));
	}
	$temp1=$this->_2money((($member['credit']*100+$member['credit1']*100)));
	$member['credit']=$temp1;
	$temp2=$this->_2money((($member['cash']+intval($member['credit2']*100))));
	$member['cash']=$temp2;
	$member['bird']=$member['birdday'] ? date("m/d",$member['birdday']) : "";
	$member['level']=$groupAry[$member['gid']];
	
	//
	$condition="";
	if($datetime){
		$conditionDay=date('Y-m-d',strtotime('-'.($datetime-1).' day'));
		$condition=" and createtime>=  ".strtotime($conditionDay." 00:00:00");
	}
	$pindex =1;
	$psize = 10;
	$list = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '{$_W['uniacid']}' $condition and cid=:a order by id desc  LIMIT " . ($pindex - 1) * $psize . ',' . $psize,array(":a"=>$member['id']));
	$total = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '{$_W['uniacid']}' $condition and cid=:a",array(":a"=>$member['id']));
	$pageall= $total <= $psize ? 1 : $total % $psize ? $total / $psize+1 : $total / $psize;
	$cost = pdo_fetchcolumn("SELECT sum(cash) FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '{$_W['uniacid']}' and usetype=1  and cid=:a",array(":a"=>$member['id']));
	die(json_encode(array('success'=>true,'item'=>$member,'list'=>$list,'pageall'=>$pageall,"cost"=> $this->_2money($cost))));
	
}elseif ($operation == 'getmembercharge') {
	$id=$_GPC['id'];
	if(!$id)die(json_encode(array('success'=>false,'msg'=>"请输入ID号")));
	$item = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition and id=:a ",array(":a"=>$id));
	if(!$item)die(json_encode(array('success'=>false,'msg'=>"请输入ID号")));
	$datetime=intval($_GPC['datetime']);
	$condition="";
	if($datetime){
		$conditionDay=date('Y-m-d',strtotime('-'.$datetime.' day'));
		$condition=" and createtime>=  ".strtotime($conditionDay." 00:00:00");
	}
	$pindex = max(1, intval($_GPC['page']));
	$psize = 10;
	$list = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '{$_W['uniacid']}' $condition and cid=:a order by id desc  LIMIT " . ($pindex - 1) * $psize . ',' . $psize,array(":a"=>$item['id']));
	$total = pdo_fetchcolumn("SELECT count(*) FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '{$_W['uniacid']}' $condition and cid=:a ",array(":a"=>$item['id']));
	die(json_encode(array('success'=>true,'item'=>$item,'list'=>$list,'total'=>$total,)));
	
}elseif ($operation == 'memberpay') {
	$id=intval($_GPC['id']);
	if(!$id)die(json_encode(array('success'=>false,'msg'=>"请输入会员卡号")));
	$item = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition and id=:a ",array(":a"=>$id));
    $membercarsh=$item['cash'];
	if(!$item)die(json_encode(array('success'=>false,'msg'=>"请输入ID号")));
	if($item['status']!=1)die(json_encode(array('success'=>false,'msg'=>"该会员卡状态异常，无法进行处理")));
	$cash=$_GPC['usetype']==1 ? intval(abs($_GPC['cash'])*(-1)*100):intval(abs($_GPC['cash'])*100);
	if($cash==0)die(json_encode(array('success'=>false,'msg'=>"请输入金额")));
    if($cfg['isgeneralbalance']){
        if($item['openid'] || $item['uid']){
            $uid=$item['uid'];
            if(!$uid)$uid=mc_openid2uid($item['openid']);
            $memberinfo=mc_credit_fetch($uid,array('credit2'));
            $membercarsh=$membercarsh+intval($memberinfo['credit2']*100);
        }

    }
	$data=array(
		"weid"=>$_W['uniacid'],
		"groupid"=>$shopid,
		"userid"=>$userid,
		"cid"=>$id,
		"usetype"=>$_GPC['usetype'],
		"paytype"=>$_GPC['paytype'],
		"startfee"=>$membercarsh,
		"cash"=>$cash,
		"gift"=>intval($_GPC['gift']*100),
		"out_trade_no"=>TIMESTAMP.mt_rand(100,999),
		"remark"=>$_GPC['remark'],
		"createtime"=>TIMESTAMP,
		"createdate"=>date("Y-m-d"),
		"status"=>0,
	);

	if($data['usetype']==1 && $membercarsh<abs($cash))die(json_encode(array('success'=>false,'msg'=>"余额不足".$membercarsh.'-'.abs($cash))));

	pdo_insert("j_hmoney_recharge",$data);
	$pid=pdo_insertid();
	if($data['usetype']==1){
		$data['paytype']=-1;
		$data['status']=1;
		$data['gift']=0;
		$data["out_trade_no"]="";
		$data['endfee']=$membercarsh-abs($cash);
		pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
        if($cfg['isgeneralbalance']){
            mc_credit_update($uid,"credit2",abs($this->_2money($cash))*(-1),array("","云门店收银系统后台消费余额￥".abs($this->_2money($cash))."元"));
        }else{
            pdo_update("j_hmoney_membercard",array("cash"=>$membercarsh-abs($cash)),array("id"=>$id));
        }
		$this->memberCardInform($id);
		die(json_encode(array('success'=>true,'pid'=>$pid)));
	}elseif($data['usetype']==2){
		$data['paytype']=-1;
		$data['status']=1;
		$data['gift']=0;
		$data["out_trade_no"]="";
		$data['endfee']=$item['cash']+abs($cash);
		pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
		pdo_update("j_hmoney_membercard",array("cash"=>$item['cash']+abs($cash)),array("id"=>$id));
		$this->memberCardInform($id);
		die(json_encode(array('success'=>true,'pid'=>$pid)));
	}elseif($data['usetype']==0){
		$qrcode=$_GPC['qrcode'];
		switch($data['paytype']){
			case 2:
			case 3:
				$data['status']=1;
				$data["out_trade_no"]="";
			break;
			case 0:
				if($cfg['isbank']){
					$bank_trade_no=TIMESTAMP.mt_rand(1000,9999);
					pdo_update("j_hmoney_recharge",array('bank_trade_no'=>$bank_trade_no),array("id"=>$pid));
					$result=Bankpay_micropay($cfg,$cash,$bank_trade_no,$data['out_trade_no'],$qrcode,$userid,$shopid);
					if($result['status'] || $result['result_code']){
						if($result['err_code']=='10003' || $result['err_code']=='USERPAYING'){
							die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid)));
						}
						die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
					}
					$data["status"]=1;
				}else{
					if(!$qrcode)die(json_encode(array('success'=>false,'msg'=>"请输入支付码")));
					$payParama=array(
						"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
						"pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
						"pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
						"outTradeNo"=>strval($data['out_trade_no']),
						"pay_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
						"sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
						"sub_mch_id"=>$shop['sub_mch_id'] ? $shop['sub_mch_id'] : $cfg['sub_mch_id'],
					);
					$pay_signkey=trim($shop['pay_signkey']) ? trim($shop['pay_signkey']) : trim($cfg['pay_signkey']);
					$pageparama=array(
						"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
						"mch_id"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
						"device_info"=>$deviceinfo,
						"nonce_str"=>getNonceStr(),
						"body"=>$shop['companyname'],
						"detail"=>"充值",
						"attach"=>"-",
						"out_trade_no"=>$payParama['outTradeNo'],
						"total_fee"=>$data['cash'],
						"fee_type"=>"CNY",
						"spbill_create_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
						"goods_tag"=>"000001",
						"auth_code"=>$qrcode,
					);
					if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
					if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
					$sign=MakeSign($pageparama,$pay_signkey);
					$pageparama['sign']=$sign;
					$xml = ToXml($pageparama);
					$response =postXmlCurl($xml, "https://api.mch.weixin.qq.com/pay/micropay", 10);
					$result=FromXml($response);
					if($result['result_code']!='SUCCESS'){
						if($result['err_code']=='USERPAYING'){
							die(json_encode(array("success"=>true,"paywait"=>true,"out_trade_no"=>$payParama['outTradeNo'],"pid"=>$pid)));
						}
						die(json_encode(array("success"=>false,"msg"=>$result['err_code_des'])));
					}
					$data["status"]=1;
				}
			break;
			case 1:
				if($cfg['isbank']){
					$bank_trade_no=TIMESTAMP.mt_rand(1000,9999);
					pdo_update("j_hmoney_recharge",array('bank_trade_no'=>$bank_trade_no),array("id"=>$pid));
					$result=Bankpay_micropay($cfg,$cash,$bank_trade_no,$data['out_trade_no'],$qrcode,$userid,$shopid);
					if($result['status'] || $result['result_code']){
						if($result['err_code']=='10003' || $result['err_code']=='USERPAYING'){
							die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid)));
						}
						die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
					}
					$data["status"]=1;
				}else{
					$qrcode=$_GPC['qrcode'];
					$payParama=array(
						"app_id"=>$shop['app_id'] ? $shop['app_id'] : $cfg['app_id'],
						"outTradeNo"=>strval($data['out_trade_no']),
						"appauthtoken"=>$shop['appauthtoken'] ? $shop['appauthtoken'] : $cfg['appauthtoken'],
						"alipay_cert"=>$cfg['alipay_cert'],
						"alipay_key"=>$cfg['alipay_key'],
						"alipay_store_id"=>$shop['alipay_store_id'] ,
						"alipid"=>$cfg['alipid'] ,
					);
					$auth_code = trim($qrcode);
					$total_amount = $data['cash'];
					$postfee=$this->_2money(($total_amount));
					require_once '../addons/j_hmoney/plug/plug_alipay/F2fpay.php';
					$f2fpay = new F2fpay();
					$response = $f2fpay->barpay($payParama['outTradeNo'],$auth_code,$postfee,$shop['companyname'],$payParama);
					$temp=(array)$response;
					$result=(array)$temp['alipay_trade_pay_response'];
					if($result['code']=="10003"){
						die(json_encode(array("success"=>true,"paywait"=>true,"out_trade_no"=>$payParama['outTradeNo'],"pid"=>$pid)));
					}elseif($result['code']=="10000"){
						$data["status"]=1;
					}else{
						die(json_encode(array("success"=>false,"msg"=>$result['sub_msg'])));
					}
				}
			break;
		}
		$data['endfee']=$item['cash']+abs($cash)+$data['gift'];
		pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
		pdo_update("j_hmoney_membercard",array("cash"=>$item['cash']+abs($cash)+$data['gift']),array("id"=>$id));
		$this->memberCardInform($id);
		die(json_encode(array("success"=>true,"out_trade_no"=>$data['out_trade_no'],"pid"=>$pid,"id"=>$id)));
	}
	die(json_encode(array('success'=>false,'msg'=>"未知错误")));
	
}elseif ($operation == 'reversepay') {
	$pid=$_GPC['pid'];
	$item = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$pid));
	$payParama=array(
		"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
		"pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
		"pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
		"pay_ip"=>$shop['pay_ip'] ? $shop['pay_ip'] : $cfg['pay_ip'],
		"sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
		"sub_mch_id"=>$shop['sub_mch_id'] ? strval($shop['sub_mch_id']) : strval($cfg['sub_mch_id']),
		"apiclient_cert"=>$shop['apiclient_cert'] ? '../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$trade['groupid']."/".$shop['apiclient_cert'] : '../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_cert'],
		"apiclient_key"=>$shop['apiclient_key'] ? '../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$trade['groupid']."/".$shop['apiclient_key'] : '../attachment/j_hmoney/cert_2/'.$_W['uniacid']."/".$cfg['apiclient_key'],
	);
	$pageparama=array(
		"appid"=>$payParama['appid'],
		"mch_id"=>$payParama['pay_mchid'],
		"nonce_str"=>getNonceStr(),
		"out_trade_no"=>$item['out_trade_no'],
	);
	if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
	if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
	$sign=MakeSign($pageparama,$payParama['pay_signkey']);
	$pageparama['sign']=$sign;
	$xml = ToXml($pageparama);
	$pemary=array("cert"=>$payParama['apiclient_cert'],"key"=>$payParama['apiclient_key'],);
	$response =postXmlAndPemCurl($xml, "https://api.mch.weixin.qq.com/secapi/pay/reverse", $pemary);
	$result=FromXml($response);
	if($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS'){
		pdo_delete("j_hmoney_recharge",array("id"=>$pid));
		die(json_encode(array("success"=>true)));
	}
	die(json_encode(array("success"=>false,"msg"=>$result['return_msg'].$result['err_code_des'])));
	
}elseif ($operation == 'waitforpass') {
	$pid=$_GPC['pid'];
	$trade = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_recharge') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$pid));
	$item = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_membercard') . " WHERE weid = '{$_W['uniacid']}' $condition and id=:a ",array(":a"=>$trade['cid']));
	if($cfg['isbank']){
		$result=Bankpay_checkpay($cfg,$trade['bank_trade_no']);
		if(!$result['status'] && !$result['result_code']){
			if($result['trade_state']=='USERPAYING' || $result['trade_state']=='10003'){
				die(json_encode(array("success"=>true,"paywait"=>true,"orderid"=>$orderid)));
			}elseif($result['trade_state']=='SUCCESS'){
				$data=array("status"=>1,'endfee'=>$item['cash']+$trade['cash']+$trade['gift']);
				pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
				pdo_update("j_hmoney_membercard",array("cash"=>$item['cash']+$trade['cash']+$trade['gift']),array("id"=>$item['id']));
				$this->memberCardInform($item['id']);
				die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$item['id'])));
			}
			die(json_encode(array("success"=>false,"msg"=>$result['trade_state'])));
		}
		die(json_encode(array("success"=>false,"msg"=>$result['message'].$result['err_msg'])));
		
	}else{
		if($item['paytype']==0){
			$payParama=array(
				"appid"=>$shop['appid'] ? $shop['appid'] : $cfg['appid'],
                "sub_appid"=>$shop['sub_appid'] ? $shop['sub_appid'] : $cfg['sub_appid'],
                "sub_mch_id"=>$shop['sub_mch_id'] ? $shop['sub_mch_id'] : $cfg['sub_mch_id'],
				"pay_mchid"=>strval($shop['pay_mchid']) ? strval($shop['pay_mchid']) : strval($cfg['pay_mchid']),
				"pay_signkey"=>$shop['pay_signkey'] ? $shop['pay_signkey'] : $cfg['pay_signkey'],
			);
			$pageparama=array(
				"appid"=>$payParama['appid'],
				"mch_id"=>strval($payParama['pay_mchid']),
				"out_trade_no"=>$trade['out_trade_no'],
				"nonce_str"=>getNonceStr(),
			);
			if($payParama['sub_appid'])$pageparama['sub_appid']=$payParama['sub_appid'];
			if($payParama['sub_mch_id'])$pageparama['sub_mch_id']=$payParama['sub_mch_id'];
			$sign=MakeSign($pageparama,$payParama['pay_signkey']);
			$pageparama['sign']=$sign;
			$xml = ToXml($pageparama);
			$response =postXmlCurl($xml, "https://api.mch.weixin.qq.com/pay/orderquery", 10);
			$result=FromXml($response);
			if($result['result_code']=='SUCCESS'){
				if($result['trade_state']=='USERPAYING'){
					die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid)));
				}elseif($result['trade_state']=='SUCCESS'){
					if($trade['status']>0){
						die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$item['id'])));
					}
					$data=array("status"=>1,'endfee'=>$item['cash']+$trade['cash']+$trade['gift']);
					pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
					pdo_update("j_hmoney_membercard",array("cash"=>$item['cash']+$trade['cash']+$trade['gift']),array("id"=>$item['id']));
					$this->memberCardInform($item['id']);
					die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$item['id'])));
				}
			}
			die(json_encode(array("success"=>false,"msg"=>$result['trade_state_desc'].$result['err_code_des'])));
			
		}else if($item['paytype']==1){
			$payParama=array(
				"app_id"=>$shop['app_id'] ? $shop['app_id'] : $cfg['app_id'],
				"pemurl"=>$cfg['pemurl'],
				"appauthtoken"=>$shop['appauthtoken'] ? $shop['appauthtoken'] : $cfg['appauthtoken'],
				"alipay_cert"=>$cfg['alipay_cert'],
				"alipay_key"=>$cfg['alipay_key'],
				"alipay_store_id"=>$shop['alipay_store_id'] ,
				"alipid"=>$cfg['alipid'] ,
			);
			require_once '../addons/j_hmoney/plug/plug_alipay/F2fpay.php';
			$cfg = $this->module['config'];
			$f2fpay = new F2fpay();
			$response = $f2fpay->query($trade['out_trade_no'],$payParama);
			$results=@json_decode(json_encode($response),true);
			$result=$results['alipay_trade_query_response'];
			if($result['code']==10003){
				die(json_encode(array("success"=>true,"paywait"=>true,"pid"=>$pid,"id"=>$item['id'])));
			}elseif($result['code']==10000){
				if($result['trade_status']=="TRADE_SUCCESS"){
					if($trade['status']>0){
						die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$item['id'])));
					}
					$data=array("status"=>1,'endfee'=>$item['cash']+$trade['cash']+$trade['gift']);
					pdo_update("j_hmoney_recharge",$data,array("id"=>$pid));
					pdo_update("j_hmoney_membercard",array("cash"=>$item['cash']+$trade['cash']+$trade['gift']),array("id"=>$item['id']));
					$this->memberCardInform($item['id']);
					die(json_encode(array("success"=>true,"paywait"=>false,"pid"=>$pid,"id"=>$item['id'])));
				}
			}
			die(json_encode(array("success"=>false,"msg"=>$result['sub_msg'])));
		}
	}
	
}elseif ($operation == 'display_gift') {
	$pindex = max(1, intval($_GPC['page']));
	$psize = 10;
	$condition = " and groupid ='".$shopid."' ";
	if (isset($_GPC['keyword']))
		$condition .= " and (title like '%" . $_GPC['keyword'] . "%' or goodsn like '%" . $_GPC['keyword'] . "%')";	
	$list = pdo_fetchall("SELECT * FROM " . tablename('j_hmoney_gift') . " WHERE weid = '{$_W['uniacid']}' $condition order by displayorder asc, id desc  LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_gift') . " WHERE weid = '{$_W['uniacid']}' $condition");
	$pageall= $total <= $psize ? 1 : $total % $psize ? $total / $psize+1 : $total / $psize;
	$gifttype=array(0=>"实物",1=>"卡券",2=>"红包",3=>"余额",4=>"抽奖");
	
}elseif ($operation == 'getgift') {	
	$id=$_GPC['id'];
	if(!$id)die(json_encode(array('success'=>false,'msg'=>"请输入ID号")));
	$condition = " and groupid ='".$shopid."' ";
	$item = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_gift') . " WHERE weid = '{$_W['uniacid']}' $condition and id=:a ",array(":a"=>$id));
	die(json_encode(array('success'=>true,'item'=>$item)));
	
}elseif ($operation == 'giftpost') {	
	$id = intval($_GPC['id']);
	$data = array(
		'weid' => $_W['uniacid'], 
		'title' => $_GPC['title'], 
		'groupid' => intval($shopid), 
		'goodsn' => $_GPC['goodsn'], 
		'store' => intval($_GPC['store']),
		'remain' => intval($_GPC['remain']),
		'gtype' => intval($_GPC['gtype']),
		'credit' => $_GPC['credit'], 
		'unitname' => $_GPC['unitname'],
		'content' => $_GPC['content'],
		'createtime' => TIMESTAMP, 
	);
	if (!empty($id)) {
		unset($data['createtime']);
		pdo_update('j_hmoney_gift', $data, array('id' => $id));
	} else {
		$data['remain']=$data['store'];
		pdo_insert('j_hmoney_gift', $data);
	}
	die(json_encode(array("success"=>true,"item"=>$item)));
	
}elseif ($operation == 'deletegift') {	
	$id = intval($_GPC['id']);
	$gift = pdo_fetch("SELECT id FROM " . tablename('j_hmoney_gift') . " WHERE  id = '$id' and groupid ='".$shopid."' ");
	if (empty($gift)) {
		message('抱歉，不存在或是已经被删除！', $this -> createWebUrl('member',array("op"=>"display_gift")), 'error');
	}
	pdo_delete('j_hmoney_gift', array('id' => $id));
	message('删除成功！', $this -> createWebUrl('member',array("op"=>"display_gift")), 'success');

}elseif ($operation == 'uploadfile') {
	load()->func('file');
	$dir_url='../attachment/j_hmoney/temp/'.$_W['uniacid']."/";
	mkdirs($dir_url);
	if ($_FILES["batchoperationfile"]["name"]){
		if(file_exists($dir_url."temp.csv"))@unlink ($dir_url."temp.xls");
		move_uploaded_file($_FILES["batchoperationfile"]["tmp_name"],$dir_url."temp.xls");
	}
	die(json_encode(array('success'=>true)));
	
}elseif ($operation == 'dealxls') {
	require "../framework/library/phpexcel/PHPExcel.php";
	$filePath='../attachment/j_hmoney/temp/'.$_W['uniacid']."/temp.xls";
	if(!file_exists($filePath))die(json_encode(array('success'=>false,'msg'=>"文件不存在")));
	$objPHPExcel = new PHPExcel();
	$PHPReader = new PHPExcel_Reader_Excel5(); 
	$PHPExcel = $PHPReader->load($filePath);
	$currentSheet = $PHPExcel->getSheet(0); 
	$allColumn = 11; 
	$allRow = $currentSheet->getHighestRow();
	$arr = array(1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G', 8 => 'H', 9 => 'I', 10 => 'J', 11 => 'K', 12 => 'L', 13 => 'M', 14 => 'N', 15 => 'O', 16 => 'P', 17 => 'Q', 18 => 'R', 19 => 'S', 20 => 'T', 21 => 'U', 22 => 'V', 23 => 'W', 24 => 'X', 25 => 'Y', 26 => 'Z');
	$list=array();
	for($currentRow = 2;$currentRow <= $allRow;$currentRow++){ 
		$temp=array();
		for($column = 0; $column<$allColumn; $column++){ 
			$val = $currentSheet->getCellByColumnAndRow($column,$currentRow)->getValue();
			if($column == 3)$val=$this->_2money(($val*100));
			if($column == 4)$val=intval($val);
			array_push($temp,strval($val));
		}
		$list[]=$temp;
	}
	die(json_encode(array('success'=>true,'list'=>$list)));
	
}elseif ($operation == 'insertexcel') {
	$rowid=$_GPC["rowid"];
	$rowidary=explode(",",$rowid);
	require "../framework/library/phpexcel/PHPExcel.php";
	$filePath='../attachment/j_hmoney/temp/'.$_W['uniacid']."/temp.xls";
	if(!file_exists($filePath))die(json_encode(array('success'=>false,'msg'=>"文件不存在")));
	$objPHPExcel = new PHPExcel();
	$PHPReader = new PHPExcel_Reader_Excel5(); 
	$PHPExcel = $PHPReader->load($filePath);
	$currentSheet = $PHPExcel->getSheet(0); 
	$allColumn = 11; 
	$allRow = $currentSheet->getHighestRow();
	$arr = array(1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F', 7 => 'G', 8 => 'H', 9 => 'I', 10 => 'J', 11 => 'K', 12 => 'L', 13 => 'M', 14 => 'N', 15 => 'O', 16 => 'P', 17 => 'Q', 18 => 'R', 19 => 'S', 20 => 'T', 21 => 'U', 22 => 'V', 23 => 'W', 24 => 'X', 25 => 'Y', 26 => 'Z');
	#卡号	微信卡号	等级	余额	积分	姓名	性别	电话	生日	备注	到期时间

	$sql="insert into ".tablename('j_hmoney_membercard')." (`weid`,`groupid`,`status`,`createtime`,`cardno`,`wxcardno`,`gid`,`cash`,`credit`,`realname`,`sex`,`mobile`,`birdday`,`remark`,`endtime`) VALUES";
	$list=array();
	for($currentRow = 2;$currentRow <= $allRow;$currentRow++){ 
		$realrow=$currentRow-1;
		if(!in_array($realrow,$rowidary))continue;
		$temp=array($_W['uniacid'],$shopid,1,TIMESTAMP);
		$rowname='';
		for($column = 0; $column<$allColumn; $column++){
			$val = $currentSheet->getCellByColumnAndRow($column,$currentRow)->getValue();
			if($column == 0)$rowname=trim($val);
			if($column == 2)$val= intval($groupAry[trim($val)]);
			if($column == 3)$val=intval($val*100);
			if($column == 4)$val=intval($val);
			array_push($temp,strval($val));
		}
		$list[$rowname]="('".implode("','",$temp)."')";
	}
	$cardnoAry=array_keys($list);
	$inList = pdo_fetchall("SELECT cardno FROM ".tablename('j_hmoney_membercard')." WHERE weid = '{$_W['uniacid']}' and groupid='".$shopid."' and  cardno in('".implode("','",$cardnoAry)."') ");
	if($inList){
		foreach($inList as $row){
			unset($list[$row['cardno']]);
		}
	}
	pdo_run($sql.implode(",",$list));
	die(json_encode(array('success'=>true,"num"=>count($list))));
	
}elseif ($operation == 'deallost') {
	$idary=$_GPC['idary'];
	pdo_update("j_hmoney_membercard",array("status"=>2)," id in (".$idary.")");
	die(json_encode(array('success'=>true)));
	
}elseif ($operation == 'excelout'){

}elseif ($operation == 'display_giftrecord'){	
	$pindex = max(1, intval($_GPC['page']));
	$psize = 10;
	$condition = " and a.groupid ='".$shopid."' ";
	if($_GPC['keyword'])$condition.= " and ( a.memberid='".$_GPC['keyword'] ."' )";
	$list = pdo_fetchall("SELECT a.*,b.realname,b.cardno FROM ".tablename('j_hmoney_giftrecord')." a left join ".tablename('j_hmoney_membercard')." b on a.memberid=b.id WHERE a.weid = '{$_W['uniacid']}' $condition order by a.id desc LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	
	$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_giftrecord') . " WHERE weid = '{$_W['uniacid']}' $condition");
	$pageall= $total <= $psize ? 1 : $total % $psize ? $total / $psize+1 : $total / $psize;
	$userlist=pdo_fetchall("SELECT id,realname FROM " . tablename('j_hmoney_user') . " WHERE pcate =:a",array(":a"=>$shopid));
	$userary=array();
	foreach($userlist as $row){
		$userary[$row['id']]=$row['realname'];
	}
	for($i=0;$i<count($list);$i++){
		$list[$i]["username"]=$userary[$list[$i]['userid']];
	}
	
} elseif ($operation == 'getgiftrecord') {
	$pindex = max(1, intval($_GPC['page']));
	$psize = 10;
	$condition = " and a.groupid ='".$shopid."' ";
	if($_GPC['keyword'])$condition.= " and ( a.memberid='".$_GPC['keyword'] ."' )";
	$list = pdo_fetchall("SELECT a.*,b.realname,b.cardno FROM ".tablename('j_hmoney_giftrecord')." a left join ".tablename('j_hmoney_membercard')." b on a.memberid=b.id WHERE a.weid = '{$_W['uniacid']}' $condition order by a.id desc LIMIT " . ($pindex - 1) * $psize . ',' . $psize);
	
	$total = pdo_fetchcolumn('SELECT COUNT(*) FROM ' . tablename('j_hmoney_giftrecord') . " WHERE weid = '{$_W['uniacid']}' $condition");
	$pageall= $total <= $psize ? 1 : $total % $psize ? $total / $psize+1 : $total / $psize;
	$userlist=pdo_fetchall("SELECT id,realname FROM " . tablename('j_hmoney_user') . " WHERE pcate =:a",array(":a"=>$shopid));
	$userary=array();
	foreach($userlist as $row){
		$userary[$row['id']]=$row['realname'];
	}
	for($i=0;$i<count($list);$i++){
		$list[$i]["username"]=$userary[$list[$i]['userid']];
	}
	die(json_encode(array('success'=>true,'list'=>$list,'pindex'=>$pindex,'total'=>$total)));
	
} elseif ($operation == 'sendgift') {
	$id=$_GPC["id"];
	$giftrecord = pdo_fetch("SELECT * FROM " . tablename('j_hmoney_giftrecord') . " WHERE weid = '{$_W['uniacid']}' and id=:a ",array(":a"=>$id));
	if($giftrecord['status']==1)die(json_encode(array("success"=>false,"msg"=>"奖品已经发送")));
	if($giftrecord['isget']==1)die(json_encode(array("success"=>false,"msg"=>"奖品已领取")));
	if($giftrecord['gtype']!=2)die(json_encode(array("success"=>false,"msg"=>"只有红包才能补发")));
	$result=$this->_sendpack($giftrecord['openid'],$giftrecord);
	if($result['errno']!=0)die(json_encode(array("success"=>false,"msg"=>$result['error'])));
	die(json_encode(array("success"=>true)));

}elseif ($operation == 'output') {

    $goodlist = pdo_fetchall("SELECT a.*,b.credit1,b.credit2,b.nickname FROM ".tablename('j_hmoney_membercard')." a left join ".tablename('mc_members')." b on a.uid=b.uid WHERE a.weid = '{$_W['uniacid']}'  order by a.id desc ");
    if(!count($goodlist))die(json_encode(array('success'=>false,'msg'=>'没有内容')));
    //
    require_once "../framework/library/phpexcel/PHPExcel.php";
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setCreator("智慧收银台")
        ->setLastModifiedBy("智慧收银台")
        ->setTitle("数据EXCEL导出")
        ->setSubject("数据EXCEL导出")
        ->setDescription("备份数据")
        ->setKeywords("excel")
        ->setCategory("result file");
    //卡号，微信卡号，姓名，电话，等级，积分，余额，状态
    $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1',"卡号")
        ->setCellValue('B1',"微信卡号")
        ->setCellValue('C1',"姓名")
        ->setCellValue('D1',"电话")
        ->setCellValue('E1',"等级")
        ->setCellValue('F1',"积分")
        ->setCellValue('G1',"余额")
        ->setCellValue('H1',"状态")
        ->setCellValue('I1',"生日");
    $num=2;
    foreach($goodlist as $row){
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A'.$num, "'".$row['cardno'])
            ->setCellValue('B'.$num, "'".$row['wxcardno'])
            ->setCellValue('C'.$num, $row['realname'])
            ->setCellValue('D'.$num, $row['mobile'])
            ->setCellValue('E'.$num, $groupAry[$row['gid']])
            ->setCellValue('F'.$num, ($row['credit']+$row['credit1']))
            ->setCellValue('G'.$num, $this->_2money($row['credit2']*100+$row['cash']))
            ->setCellValue('H'.$num, $row['status'] ? "正常":"-")
            ->setCellValue('I'.$num, $row['birdday']);
        $num++;
    }

    $objPHPExcel->getActiveSheet()->setTitle('会员列表');
    $objPHPExcel->setActiveSheetIndex(0);
    ob_end_clean();
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition:attachment;filename="member_temp.xls"');
    header('Cache-Control:max-age=0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit();
}
include $this->template('web/'.$cfg['floder'].'/member');









